# -*- coding: utf-8 -*-
import json
import os
import re

import xlrd

from utils.langconv import Converter
from utils.constent import stop_word_path

current_path = os.path.dirname(__file__)
root_path = os.path.split(current_path)


def error(message=''):
    resp = dict()
    resp['status'] = 'error'
    resp['message'] = message
    return json.dumps(resp).encode().decode('unicode_escape')


def success(message='', **kwargs):
    resp = dict()
    resp['status'] = 'success'
    resp['message'] = message
    for key, parameter in kwargs.items():
        resp[key] = parameter
    return json.dumps(resp).encode().decode('unicode_escape')


def check_parameters(param=None, *args):
    try:
        for val in args:
            if (param is None) or (val not in param):
                return False
            if len(param[val]) == 0:
                return False
    except Exception as e:
        pass
    return True


def is_json(text):
    try:
        json.loads(text)
    except ValueError:
        return False
    return True


def find_last(string, chars):
    last_pos = -1
    while True:
        pos = string.find(chars, last_pos + 1)
        if pos == -1:
            return last_pos
        last_pos = pos


def cut_sent_by_newline(text):
    """
    根据换行符切分文本
    :param text: 
    :return: 
    """"""
    :param text: 
    :return: 
    """
    text = text.rstrip()
    return text.split('\n')


def cut_sent(text):
    """中文分句"""
    # 单字符断句
    text = re.sub('([。！？?!;；])([^”’])', r"\1\n\2", text)
    text = text.rstrip()
    return text.split('\n')


def cut_sent_seg(text, max_lenth=0, max_bd=''):
    """中文分句"""
    # 单字符断句
    def _cut_t(matched):
        st = matched.group(0)
        if '.' in st:
            st = st.replace('.', '\n')
        elif '．' in st:
            st = st.replace('．', '\n')
        else:
            st = '\n'
        return st
    text = re.sub('[。！？?!;；]|[^0-9]([\.．])[^0-9]', _cut_t, text) # r"\1\n\2"
    text = text.rstrip()
    res = text.split("\n")
    if max_lenth == 0:
        return res
    temp_list = []
    for r in res:
        if len(r) > max_lenth:
            rs = r.split(max_bd)
            temp_list.extend(rs)
            continue
        temp_list.append(r)
    return temp_list


def del_space(text):
    """去除空格"""
    text = text.replace('\n', '').replace('\r', '').replace('\t', '').replace(' ', '').replace(' ', '').replace('　+', '')
    return text


def full_to_half(s):
    """
    全角转半角
    """
    n = []
    for char in s:
        num = ord(char)
        if num == 0x3000:
            num = 32
        elif 0xFF01 <= num <= 0xFF5E:
            num -= 0xfee0
        char = chr(num)
        n.append(char)
    # 英文分号替换为中文分号
    s = ''.join(n).replace('•', '·').replace('・', '·')  # .replace(';', '；')
    return s


def half_to_full(s):
    """
    半角转全角
    :param s:
    :return:
    """
    n = []
    for char in s:
        num = ord(char)
        if num == 23:
            num = 12288
        elif 32 <= num <= 126:
            num += 65248
        char = chr(num)
        n.append(char)
    return ''.join(n)


def Traditional2Simplified(sentence):
    """
    中文繁体转简体
    """
    sentence = Converter('zh-hans').convert(sentence).replace('馀', '余')
    return sentence


def check_chinese(sentence):
    """检查是否有中文"""
    if len(re.findall('.*?[\u4E00-\u9FA5]+.*?', sentence)) == 0:
        return False
    return True


def get_excel_data(file_path, sheet_index=0, start_row=0):
    """
    获取Excel数据
    :param file_path:
    :param cols:
    :return:
    """
    excel_file = xlrd.open_workbook(file_path, encoding_override='utf-8')
    sheet = excel_file.sheet_by_index(sheet_index)
    datas = []
    for ind in range(start_row, sheet.nrows):
        datas.append(sheet.row_values(ind))
    return datas



#
# if __name__ == '__main__':
#     import time
#     print(time_to_str(round(time.time())))
